<template>
	<view class="bills_box">
		<template v-if="mountTip">
			<Tips/>
		</template>
		<view class="header" v-if="!isChooseBill">
			<view class="type_box">
				<view class="type" @click="clickBillTypeFun">
					<view class="name text_ellipsis">
						{{showBillTypeName}}
					</view>
					<view class="icon">
						<MyIcons size="40rpx" :src="joinSystemPath('menu.png')"/>
					</view>
				</view>
				<view class="type" @click="clickUserTypeFun">
					<view class="name text_ellipsis">
						{{showUserName}}
					</view>
					<view class="icon">
						<MyIcons size="40rpx" :src="joinSystemPath('dormitory.png')"/>
					</view>
				</view>
			</view>
			<view class="info">
				<view class="time">
					<picker fields="month" mode="date" :value="date" @change="bindDateChange">
						<view class="uni-input">{{date}}</view>
					</picker>
				</view>
				<view class="down">
					<MyIcons size="30rpx" :src="joinSystemPath('line_h.png')"/>
				</view>
				<view class="data text_ellipsis">
					{{`总收入:${parseFloat(allInOut?.allIn) || '0.00'} 总支出:${parseFloat(allInOut?.allOut) || '0.00'}`}}
				</view>
			</view>
		</view>
		<view class="choose" v-if="!isChooseBill">
			<uni-segmented-control 
				:current="formData.in_out_type" 
				:values="items" 
				style-type="button"
				:active-color="primary_hot_color" 
				@clickItem="onChooseFun" />
		</view>
		<view class="content">
			<scroll-view
				scroll-y="true" 
				:show-scrollbar="false"
				class="scroll-Y"
				@scrolltolower="lower">
				<BillCard @clickBillCardEmit="clickBill" v-for="(item,index) in allBills" :itemIndex="index" :billData="item" :key="item.id">
				</BillCard>
				<view class="load_box">
					<uni-load-more :content-text="contentText" iconType="circle" :color="primary_hot_color" :status="loadingStatus" />
				</view>
				<view v-if="!allBills.length">
					<MyNull img="nullMemo.png"/>
				</view>
			</scroll-view>
		</view>
		<MyPopub :isOpenPopub="openPopubFlag" :slotsNums="1">
			<template #1>
				<BillTypeCard
					:checkedBillType="formData.billType_id" 
					@chooseBillTypeFunEmit="chooseBillTypeFun"
					:showBillTypeList="showBillTypeList"/>
			</template>
		</MyPopub>
		<MyPopub :isOpenPopub="openPopubFlagByUser" :slotsNums="1">
			<template #1>
				<BillTypeCard
					:checkedBillType="formData.user_id" 
					iconRadius="35rpx"
					:joinIconFun="joinAvatarPath"
					@chooseBillTypeFunEmit="chooseUserTypeFun"
					:showBillTypeList="allJoiner"/>
			</template>
		</MyPopub>
		<MyPopub height="calc(50vh)" :isOpenPopub="openPopubFlagByBillInfo" :slotsNums="1">
			<template #1>
				<BillInfo
					@deleteBillEmit="deleteBillFun"
					@editorBillEmit="editorBillFun"
					:billInfo="chooseBillInfo"/>
			</template>
		</MyPopub>
		<MyModal :openModalFlag="modalIsDeleteBillFlag" :okFun="submitDeleteBillFun">
			<template #title>
				确认删除吗
			</template>
		</MyModal>
	</view>
</template>

<script setup>
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		ref,
		computed,
		nextTick
	} from 'vue'
	
	import {
		joinSystemPath,
		joinAvatarPath
	} from '@/utils/imgJoinName.js'
	import {
		getMonthDay,
	} from '@/utils/changeData.js'
	
	import BillCard from '@/components/Dormitory/BillCard/BillCard.vue'
	import MyPopub from '@/components/MyPopub/MyPopub.vue'
	import BillTypeCard from '@/components/Dormitory/BillTypeCard/BillTypeCard.vue'
	import BillInfo from '@/components/Dormitory/BillInfo/BillInfo.vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyNull from '@/components/MyNull/MyNull.vue'
	import AdBanner from '@/components/AdBanner/AdBanner.vue'
	
	import {dynamicStyleStore} from '@/stores/dynamicStyle.js'
	import {userStore} from '@/stores/user'
	
	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	
	import {
		verifyIsLastOpenPhone
	} from '@/hooks/verify.js'
	
	import { DefaultPhone } from '../../../enum/GlobalEnum'
	
	const dynamicStyle_store = dynamicStyleStore()
	const user_store = userStore()
	const dormitoryModel = new DormitoryModel()

	const {
		primary_hot_color,
		primary_light_color,
		primary_main_bgc
	} = dynamicStyle_store.dormitoryStyle
	
	const props=defineProps({
		isChooseBill:{
			type:Boolean,
			default:false
		},
		mountTip:{
			type:Boolean,
			default:true
		}
	})
	const emits=defineEmits(['chooseBillByEstateEmit'])
	
	const dormitoryAllId=uni.getStorageSync('homeData')
	const noBindPhone = computed(()=>user_store.userInfo.phone === DefaultPhone)
	
	const formData=ref({
		limit:10,
		page:0,
		orderBy:'createAt.desc',
		user_id:'all',
		in_out_type:0,
		billType_id:'all',
		timeStart:'1999-01-01',
		timeEnd:'9999-01-01'
	})
	
	const allBills=ref([])
	const loadingStatus = ref('more')
	const contentText =ref({
		contentdown: '下滑加载更多',
		contentrefresh: '加载账单中',
		contentnomore: '没有更多账单了'
	})
	const isAllowGet=ref(true)
	const isAddBillPageGo = ref(false)
	const init=()=>{
		formData.value.page=0
		allBills.value = []
		isAllowGet.value = true
	}
	//获取所有账单
	const getALlBills=async()=>{
		loadingStatus.value = 'loading'
		const {data,success} = await dormitoryModel.getAllBills(formData.value,dormitoryAllId.dormitory_id)
		if(success){
			allBills.value=[...allBills.value,...data]
			if(!data.length || data.length<formData.value.limit){
				isAllowGet.value = false
				loadingStatus.value = 'nomore'
			}else{
				loadingStatus.value = 'more'
			}
			// isAddBillPageGo.value && noBindPhone.value && !verifyIsLastOpenPhone() && uni.$emit('openPhonePopubFlag',false,false)
		}
	}
	
	//滚动到了底部
	const lower=()=>{
		if(!isAllowGet.value) return
		formData.value.page++
		getALlBills()
	}
	
	const bindDateChange =(e)=>{
		const dateArr = e.detail.value.toString().split('-')
		const year = dateArr[0]
		const dayEnd = getMonthDay(Number(dateArr[0]),Number(dateArr[1]))
		formData.value.timeStart = e.detail.value + '-01'
		formData.value.timeEnd = e.detail.value+'-'+dayEnd
		date.value = e.detail.value
		init()
		getAllInOut()
		getALlBills()
	}
	const getDate=(type)=>{
	            const date = new Date();
	            let year = date.getFullYear();
	            let month = date.getMonth() + 1;
	
	            month = month > 9 ? month : '0' + month;
				
				// formData.value.timeStart = year + '-' + month + '-01'
				// formData.value.timeEnd = year + '-' + month+'-'+getMonthDay(year,month)
				
	            return `${year}-${month}`;
	        }
	const date = ref(getDate({format: true}))
	
	const openPopubFlag = ref(0)
	const openPopubFlagByUser = ref(0)
	const items = ref(['支出','收入'])
	//选择收入支出类型
	const onChooseFun=(e)=>{
		formData.value.in_out_type = e.currentIndex
		showBillTypeList.value = billTypeList.value.filter(item=>item.in_out_type === formData.value.in_out_type)
		showBillTypeList.value.unshift({
			id:'all',
			name:'全部类型'
		})
		formData.value.billType_id=showBillTypeList.value[0].id
		showBillTypeName.value='全部类型'
		init ()
		getALlBills()
	}
	const allJoiner=ref([])
	const showUserName=ref('全部室友')
	//点击用户类型再去加载所有用户
	const clickUserTypeFun=async()=>{
		if(!allJoiner.value.length){
			const {data,success} = await dormitoryModel.getAllJoiner({
				limit:1000,
				page:0,
				orderBy:'createAt.desc'
			},dormitoryAllId.dormitory_id)
			if(success){
				allJoiner.value = data
				allJoiner.value.map(item=>{
					item['id']=item.user_id
					item['name']=item.nick_name_by_dormitory
					item['iconPath']=item.user_avatar
				})
				allJoiner.value.unshift({
					id:'all',
					name:'全部室友'
				})
			}
		}
		openPopubFlagByUser.value=Math.random()
	}
	//选择用户类型
	const chooseUserTypeFun=(e)=>{
		showUserName.value=e.name
		formData.value.user_id = e.id
		openPopubFlagByUser.value = -Math.random()
		init()
		getALlBills()
		getAllInOut()
	}
	//点击账单类型后再去加载所有类型
	const clickBillTypeFun=()=>{
		!billTypeList.value.length && getBillTypeList()
		openPopubFlag.value = Math.random()
	}
	//选择账单类型
	const chooseBillTypeFun=(e)=>{
		showBillTypeName.value = e.name
		formData.value.billType_id = e.id
		openPopubFlag.value = -Math.random()
		init()
		getALlBills()
	}
	
	//账单类型
	const billTypeList = ref([])
	const allInOut=ref({})
	const showBillTypeList=ref([])
	const showBillTypeName=ref('全部类型')
	
	const getAllInOut=async()=>{
		const _data = {
			timeStart:formData.value.timeStart,
			timeEnd:formData.value.timeEnd,
			user_id:formData.value.user_id
		}
		const {data,success} = await dormitoryModel.getAllInOut(_data,dormitoryAllId.dormitory_id)
		if(success){
			allInOut.value = data
		}
	}

	const getBillTypeList=async(chooseBillTypeId)=>{
		const {data,success} = await dormitoryModel.getBillTypeList({},dormitoryAllId.dormitory_id)
		if(success){
			billTypeList.value = data
			showBillTypeList.value = billTypeList.value.filter(item=>item.in_out_type === formData.value.in_out_type)
			showBillTypeList.value.unshift({
				id:'all',
				name:'全部类型'
			})
			showBillTypeName.value='全部类型'
			formData.value.billType_id= chooseBillTypeId || showBillTypeList.value[0].id
		}
	}
	
	//账单详细信息
	const chooseBillInfo=ref({})
	const openPopubFlagByBillInfo=ref(0)
	const clickBill=(item)=>{
		if(props.isChooseBill){
			emits('chooseBillByEstateEmit',item)
		}else{
			openPopubFlagByBillInfo.value=Math.random()
			chooseBillInfo.value = item 
		}
	}
	const modalIsDeleteBillFlag=ref(0)
	//提交删除
	const submitDeleteBillFun=async()=>{
		const {data,success} = await dormitoryModel.deleteBill({},chooseBillInfo.value.id)
		if(success){
			uni.$emit('tips',data,'success')
			const index=allBills.value.findIndex(item=>{
				return item.id === chooseBillInfo.value.id
			})
			if(index!==-1){
				allBills.value.splice(index,1)
				getAllInOut()
			}
		}
	}
	//点击了删除按钮
	const deleteBillFun=()=>{
		openPopubFlagByBillInfo.value=-Math.random()
		modalIsDeleteBillFlag.value=Math.random()
	}
	//点击了编辑按钮
	const editorBillFun=()=>{
		openPopubFlagByBillInfo.value=-Math.random()
		uni.navigateTo({
			url:`/pages/Dormitory/AddBill/AddBill?bill_id=${chooseBillInfo.value.id}`
		})
		uni.setStorageSync('editorBill',chooseBillInfo.value)
	}
	
	onShow(()=>{
		
	})
	
	onLoad((opt)=>{
		const {isAddBillPageGo:_isAddBillPageGo} = opt
		isAddBillPageGo.value = _isAddBillPageGo
		
		init()
		getAllInOut()
		getALlBills()
	})
</script>

<style lang="less">
	.text_ellipsis {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.bills_box{
		background-color: v-bind(primary_main_bgc);
		.header{
			z-index: 4;
			padding: 20rpx;
			background-color: v-bind(primary_hot_color);
			position: fixed;
			width: 100%;
			.type_box{
				width: 94%;
				display: flex;
				.type{
					width: 30%;
					border: 1px solid #FFFFFF;
					display: flex;
					align-items: center;
					padding: 5rpx;
					border-radius: 10rpx;
					margin: 15rpx 0;
					.name{
						width: 70%;
						text-align: center;
						font-size: 30rpx;
						color: #FFFFFF;
						border-right: 1px solid #FFFFFF;
					}
					.icon{
						width: 30%;
						display: flex;
						justify-content: center;
						align-items: center;
					}
				}
				.type:hover{
					border: 1px solid v-bind(primary_light_color);
				}
				.type:nth-child(2){
					margin-left: 10rpx;
				}
			}
			.info{
				width: 90%;
				margin-left: 20rpx;
				display: flex;
				.time{
					color: #FFFFFF;
					font-size: 30rpx;
					width: 20%;
					display: flex;
					justify-content: center;
				}
				.down{
					display: flex;
					justify-content: center;
					align-items: center;
					width: 5%;
					margin: 0 4rpx;
				}
				.data{
					font-size: 30rpx;
					color: #d9dede;
					width: 75%;
				}
			}
		}
		.choose{
			padding: 20rpx 20rpx 0 20rpx;
			padding-top: 190rpx;
			background-color: v-bind(primary_main_bgc);
			z-index: 2;
		}
		.content{
			padding: 0 20rpx 40rpx 20rpx;
			background-color: v-bind(primary_main_bgc);
			.scroll-Y {
				height: calc(80vh);
				.load_box{
					margin-bottom: 3%;
				}
			}
		}
	}
</style>
